import 'dart:async';

import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final String initParams = window.defaultRouteName;

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter混合开发',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(
        title: 'Flutter混合开发',
        initParamsRoutname: initParams,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title, this.initParamsRoutname}) : super(key: key);
  final String title;
  final String initParamsRoutname;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //三种通信方法
  //一、初始化 EventChannel
  static const EventChannel _eventChannelPlugin =
      EventChannel('EventChannelPlugin');

  //二、初始化 MethodChannel
  static const MethodChannel _methodChannelPlugin =
      MethodChannel('MethodChannelPlugin');

  //三、初始化 BasicMessageChannel
  static const BasicMessageChannel<String> _basicMessageChannelPlugin =
      const BasicMessageChannel('BasicMessageChannelPlugin', StringCodec());

  String showMessage = '';
  StreamSubscription _streamSubscription;
  bool _isMethodChannelPlugin = false; //是否使用 MethodChannel 通信

  @override
  void initState() {
    //注册监听
    _eventChannelPlugin.receiveBroadcastStream('123').listen(
          _onToDart,
          onError: _onToDartError,
        );

    //使用 BasicMessageChannel 接收来自 Native 的消息后，并向 Native 回复消息
    _basicMessageChannelPlugin
        .setMessageHandler((String message) => Future<String>(() {
              setState(() {
                showMessage = "BasicMessageChannel:" + message;
              });
              return "收到 Nat"
                  "ive 消息：" + message;
            }));

    super.initState();
  }

  void _onToDart(message) {
    setState(() {
      showMessage = message;
    });
  }

  void _onToDartError(error) {
    print(error);
  }

  @override
  void dispose() {
    //及时回收资源
    _streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(color: Colors.lightBlueAccent),
          margin: EdgeInsets.only(top: 120.0),
          child: Column(
            children: <Widget>[
              SwitchListTile(
                value: _isMethodChannelPlugin,
                onChanged: _onChannerChange,
                title: Text(_isMethodChannelPlugin
                    ? "MethodChannelPlugin"
                    : "BasicMessageChannelPlugin"),
              ),
              TextField(
                onChanged: _onTextChange,
                decoration: InputDecoration(
                    focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.white),
                    ),
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey),
                    )),
              ),
              Text('收到初始化参数 initParams:${widget.initParamsRoutname}',),
              Text(
                'Native 传来的数据：' + showMessage,
              )
            ],
          ),
        ));
  }

  void _onChannerChange(bool value) {
    setState(() {
      _isMethodChannelPlugin = value;
    });
  }

  void _onTextChange(String value) async {
    String reponse;
    try {
      if (_isMethodChannelPlugin) {
        reponse = await _methodChannelPlugin.invokeMethod('send', value);
      } else {
        //使用 BasicMessageChannel 向 Native 发送消息，并接受 Native的回复
        reponse = await _basicMessageChannelPlugin.send(value);
      }
    } on PlatformException catch (e) {
      print(e);
    }
  }
}
